import { getUserByLogin } from "../../../../services/user";
import jwt from "jsonwebtoken";
import { GraphQLError } from 'graphql'

require('dotenv').config()
const signingKey = process.env.JWT_SECRET ?? "secret.key";
const issuer = process.env.JWT_ISSUER;

import type { MutationResolvers } from "./../../../types.generated";
export const Login: NonNullable<MutationResolvers["Login"]> = async (
  _parent,
  _arg,
  _ctx
) => {
  /* Implement Mutation.Login resolver logic here */
  const user = getUserByLogin(_arg.userName, _arg.password);
  if (!user) {
    throw new GraphQLError("Invalid credentials");
  }

  var token = jwt.sign({ username: _arg.userName }, signingKey, {
    subject: user.id,
    issuer: issuer,
  });
  var decoded = jwt.verify(token, signingKey);
  console.log(decoded);
  return token;
};
